<?php

require_once('myPDO.php');
require_once 'global.php';
require_once 'mp3.php';
require_once 'playlists.php';

class Usuario
{
    private $_id;
    private $_username;
    private $_password;
    private $_mail;
    private $_avatar;

    public static function findByUsername($username) {
        $dsn = DSN_BBDD;
        $user = USER_BBDD;
        $password = PASS_BBDD;

        try {
            $dbh = new myPDO($dsn, $user, $password);
        } catch (PDOException $e) {
            echo 'Connection failed: ' . $e->getMessage();
        }

        $sql = 'SELECT id FROM usuaris WHERE username= :variable';
        
        $sth = $dbh->prepare($sql);
        $bindParam = $sth->bindParam(':variable', $username);

        $sth->execute();
        $result = $sth->fetch(PDO::FETCH_ASSOC);

        $sth->closeCursor();
        $dbh = null;

        $userid = $result['id'];
        if (!$userid) {
            throw new Exception("no such user");
        }
        
        return new Usuario($userid);

    }
    
    
     public function __construct($userid = false)
     {
        if(!$userid) return;
         
        $dsn = DSN_BBDD;
        $user = USER_BBDD;
        $password = PASS_BBDD;

        try {
            $dbh = new myPDO($dsn, $user, $password);
        } catch (PDOException $e) {
            echo 'Connection failed: ' . $e->getMessage();
        }
        
        $sql = 'SELECT * FROM usuaris WHERE id= :id';
        
        $sth = $dbh->prepare($sql);
        $bindParam = $sth->bindParam(':id', $userid);

        $sth->execute();
        $result = $sth->fetch(PDO::FETCH_ASSOC);

        $sth->closeCursor();
        $dbh = null;
        
        if (!$result) throw new Exception("Identifiador de usuario: '{$userid}' no existe.");
        foreach ($result as $attr => $value) $this->{'_'.$attr} = $value;

     }
     
     
     public function insert() {
                 
        $dsn = DSN_BBDD;
        $user = USER_BBDD;
        $password = PASS_BBDD;

        try {
            $dbh = new myPDO($dsn, $user, $password);
        } catch (PDOException $e) {
            echo 'Connection failed: ' . $e->getMessage();
        }
        
        $sql = 'INSERT INTO usuaris (username, password, mail, avatar) VALUES (:1, :2, :3, :4)';
        
        $sth = $dbh->prepare($sql);
        $bindParam = $sth->bindParam(':1', $this->_username);
        $bindParam = $sth->bindParam(':2', $this->_password);
        $bindParam = $sth->bindParam(':3', $this->_mail);
        $bindParam = $sth->bindParam(':4', $this->_avatar);
        
        $sth->execute();
        $sth->closeCursor();
        $dbh = null;         
     }
     
     
     public function update() {
        if (!$this->_id) throw new Exception("User needs userid to call update.");
         
        $dsn = DSN_BBDD;
        $user = USER_BBDD;
        $password = PASS_BBDD;
        
        try {
            $dbh = new myPDO($dsn, $user, $password);
        } catch (PDOException $e) {
            echo 'Connection failed: ' . $e->getMessage();
        }
        
        $sql = 'UPDATE usuaris SET username= :2, password= :3, mail= :4, avatar= :5 WHERE id= :1';
        
        $sth = $dbh->prepare($sql);
        $bindParam = $sth->bindParam(':1', $this->_id);
        $bindParam = $sth->bindParam(':2', $this->_username);
        $bindParam = $sth->bindParam(':3', $this->_password);
        $bindParam = $sth->bindParam(':4', $this->_mail);
        $bindParam = $sth->bindParam(':5', $this->_avatar);
        
        $sth->execute();
        $sth->closeCursor();
        $dbh = null; 
     }
     
     public function delete() {
         if (!$this->_id) throw new Exception("User object has no userid");
         
        $dsn = DSN_BBDD;
        $user = USER_BBDD;
        $password = PASS_BBDD;

        try {
            $dbh = new myPDO($dsn, $user, $password);
        } catch (PDOException $e) {
            echo 'Connection failed: ' . $e->getMessage();
        }
        
        $sql = 'DELETE FROM usuaris WHERE id= :1';
        
        $sth = $dbh->prepare($sql);
        $bindParam = $sth->bindParam(':1', $this->_id);
        
        $sth->execute();
        $sth->closeCursor();
        $dbh = null; 
     }
     
     

     
    private function comprova_username($u) {
        if (!empty($u) && strlen($u) <= 20)
            return true;
        else
            throw new Exception('ERROR: username');
    }

    private function comprova_password($p)
    {
        if (!empty($p) && strlen($p) == 32)
            return true;
        else
            throw new Exception('ERROR: password');
    }

    
    private function comprova_mail($m)
    {
        if (!empty($m) &&
            strlen($m) <= 50 &&
            preg_match('/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9]+([.][a-zA-Z0-9]+)*[.][a-zA-Z]{2,4}$/', $m)
           )
            return true;
        else
            throw new Exception('ERROR: mail');
    }  
    
    
    /* SETERS */

    public function set_username($u)
    {
        if ($this->comprova_username($u))
            $this->_username = $u;
    }

    public function set_password($p)
    {
        $p = md5(SALT.$p.SALT);
        if ($this->comprova_password($p))
            $this->_password = $p;
    }

    public function set_mail($m)
    {
        if ($this->comprova_mail($m))
            $this->_mail = $m;
    }

    public function set_avatar($a)
    {
        $this->_avatar = $a;
    }

    /* GET */

    public function get_id() {
        return $this->_id;
    }

    public function get_username() {
        return $this->_username;
    }

    public function get_password() {
        return $this->_password;
    }

    public function get_mail() {
        return $this->_mail;
    }

    public function get_avatar() {
        return $this->_avatar;
    }
    
    public function songs() {
        $dsn = DSN_BBDD;
        $user = USER_BBDD;
        $password = PASS_BBDD;

        try {
            $dbh = new mypdo($dsn, $user, $password);
        } catch (pdoexception $e) {
            echo 'connection failed: ' . $e->getmessage();
        }

        $sql = 'SELECT mp3 FROM usuarismp3 WHERE usuari= :variable';

        $sth = $dbh->prepare($sql);
        $bindparam = $sth->bindparam(':variable', $this->_id);

        $sth->execute();
        $result = $sth->fetchAll(PDO::FETCH_ASSOC);

        $sth->closecursor();
        $dbh = null;

        $cancoresult = null;
        foreach ($result as $array) {
            foreach ($array as $id) {
                $cancoresult[] = new Mp3($id);
            }
        }
        return $cancoresult; 
    }

    public function add_song($idsong) {
        $dsn = DSN_BBDD;
        $user = USER_BBDD;
        $password = PASS_BBDD;

        try {
            $dbh = new myPDO($dsn, $user, $password);
        } catch (PDOException $e) {
            echo 'Connection failed: ' . $e->getMessage();
        }

        $sql = 'INSERT INTO usuarismp3 (usuari, mp3) VALUES (:1, :2)';

        $sth = $dbh->prepare($sql);
        $bindParam = $sth->bindParam(':1', $this->_id);
        $bindParam = $sth->bindParam(':2', $idsong);

        $sth->execute();
        $sth->closeCursor();
        $dbh = null;
    }

    public function delete_song($idsong) {
        $dsn = DSN_BBDD;
        $user = USER_BBDD;
        $password = PASS_BBDD;

        try {
            $dbh = new myPDO($dsn, $user, $password);
        } catch (PDOException $e) {
            echo 'Connection failed: ' . $e->getMessage();
        }

        $sql = 'DELETE FROM usuarismp3 WHERE usuari= :1 AND mp3= :2';

        $sth = $dbh->prepare($sql);
        $bindParam = $sth->bindParam(':1', $this->_id);
        $bindParam = $sth->bindParam(':2', $idsong);

        $sth->execute();
        $sth->closeCursor();
        $dbh = null;

        Mp3::refreshprivate($idsong);
    }


     public function set_public($idsong) {
        $dsn = DSN_BBDD;
        $user = USER_BBDD;
        $password = PASS_BBDD;

        try {
            $dbh = new myPDO($dsn, $user, $password);
        } catch (PDOException $e) {
            echo 'Connection failed: ' . $e->getMessage();
        }

        $sql = 'UPDATE usuarismp3 SET public=1 WHERE usuari= :1 AND mp3= :2';

        $sth = $dbh->prepare($sql);
        $bindParam = $sth->bindParam(':1', $this->_id);
        $bindParam = $sth->bindParam(':2', $idsong);

        $sth->execute();
        $sth->closeCursor();
        $dbh = null;

        Mp3::refreshprivate($idsong);
    }

    public function set_private($idsong) {
        $dsn = DSN_BBDD;
        $user = USER_BBDD;
        $password = PASS_BBDD;

        try {
            $dbh = new myPDO($dsn, $user, $password);
        } catch (PDOException $e) {
            echo 'Connection failed: ' . $e->getMessage();
        }

        $sql = 'UPDATE usuarismp3 SET public=0 WHERE usuari= :1 AND mp3= :2';

        $sth = $dbh->prepare($sql);
        $bindParam = $sth->bindParam(':1', $this->_id);
        $bindParam = $sth->bindParam(':2', $idsong);

        $sth->execute();
        $sth->closeCursor();
        $dbh = null;

        Mp3::refreshprivate($idsong);
    }
    
}
?>
